from fastapi import APIRouter, status, Query, Depends, HTTPException
from typing import Optional, List
from app.modules.roles.models import RoleModel
from app.modules.roles.schemas import (
    RoleCreateInput, RoleCreatedResponse, RoleUpdate, 
    RoleInfo, RoleDetailInfo, RoleListResponse, RoleUsersResponse,
    RolePermissionUpdate, RoleBatchUpdate, RoleQueryParams
)
from app.modules.roles.services import RoleService
from app.core.responses import success_response, error_response
from app.core.exceptions import BusinessException
from app.core.dependencies import get_current_user
from app.modules.users.models import UserModel

router = APIRouter(
    prefix="/api/roles", 
    tags=["角色管理"]
)


@router.post("/", summary="创建角色", response_model=RoleCreatedResponse)
async def create_role(
    role_in: RoleCreateInput, 
    current_user: UserModel = Depends(get_current_user)
):
    """
    创建新角色
    
    - **name**: 角色名称
    - **code**: 角色编码（唯一）
    - **description**: 角色描述
    - **permissions**: 权限编码列表
    - **sort_order**: 排序
    - **is_active**: 是否激活
    - **remark**: 备注
    """
    result = await RoleService.create_role(role_in)
    return success_response(
        data=result,
        message="角色创建成功",
        code=status.HTTP_201_CREATED
    )


@router.get("/", summary="获取角色列表", response_model=RoleListResponse)
async def get_role_list(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    name: Optional[str] = Query(None, description="角色名称"),
    code: Optional[str] = Query(None, description="角色编码"),
    is_active: Optional[bool] = Query(None, description="是否激活"),
    is_system: Optional[bool] = Query(None, description="是否系统角色")
):
    """获取角色分页列表，支持多种查询条件"""
    query_params = RoleQueryParams(
        name=name,
        code=code,
        is_active=is_active,
        is_system=is_system
    )
    
    total, items = await RoleService.get_role_list(
        skip=(page - 1) * size, 
        limit=size,
        query_params=query_params
    )
    return success_response(data={"total": total, "items": items})


@router.get("/active", summary="获取激活角色列表")
async def get_active_roles():
    """获取所有激活的角色"""
    roles = await RoleService.get_active_roles()
    return success_response(data=roles)


@router.get("/system", summary="获取系统角色列表")
async def get_system_roles():
    """获取系统角色列表"""
    roles = await RoleService.get_system_roles()
    return success_response(data=roles)


@router.get("/custom", summary="获取自定义角色列表")
async def get_custom_roles():
    """获取自定义角色列表"""
    roles = await RoleService.get_custom_roles()
    return success_response(data=roles)


@router.get("/with-permissions", summary="获取角色及权限信息")
async def get_roles_with_permissions():
    """获取所有角色及其权限信息"""
    roles = await RoleService.get_roles_with_permissions()
    return success_response(data=roles)


@router.get("/{role_id}", summary="获取角色详情", response_model=RoleDetailInfo)
async def get_role_detail(role_id: int):
    """根据角色ID获取角色详情（包含权限对象）"""
    role = await RoleService.get_role_detail(role_id)
    return success_response(data=role)


@router.get("/{role_id}/users", summary="获取角色用户列表", response_model=RoleUsersResponse)
async def get_role_users(
    role_id: int,
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量")
):
    """获取指定角色的用户列表"""
    total, items = await RoleService.get_role_users(
        role_id=role_id,
        skip=(page - 1) * size, 
        limit=size
    )
    return success_response(data={"total": total, "items": items})


@router.patch("/{role_id}", summary="更新角色信息", response_model=RoleInfo)
async def update_role(
    role_id: int, 
    role_in: RoleUpdate,
    current_user: UserModel = Depends(get_current_user)
):
    """
    更新角色信息
    
    - 系统角色不允许修改
    - 角色编码不能重复
    - 权限编码必须存在
    """
    result = await RoleService.update_role(role_id, role_in)
    return success_response(data=result, message="角色更新成功")


@router.delete("/{role_id}", summary="删除角色")
async def delete_role(
    role_id: int,
    current_user: UserModel = Depends(get_current_user)
):
    """
    删除角色
    
    - 系统角色不允许删除
    - 有用户使用时无法删除
    """
    await RoleService.delete_role(role_id)
    return success_response(message="角色删除成功")


@router.patch("/{role_id}/permissions", summary="更新角色权限", response_model=RoleInfo)
async def update_role_permissions(
    role_id: int,
    permission_data: RolePermissionUpdate,
    current_user: UserModel = Depends(get_current_user)
):
    """
    更新角色权限（完全替换）
    
    - 系统角色不允许修改权限
    - 权限编码必须存在
    """
    result = await RoleService.update_role_permissions(role_id, permission_data.permissions)
    return success_response(data=result, message="角色权限更新成功")


@router.post("/{role_id}/permissions", summary="为角色添加权限", response_model=RoleInfo)
async def add_role_permissions(
    role_id: int,
    permission_data: RolePermissionUpdate,
    current_user: UserModel = Depends(get_current_user)
):
    """
    为角色添加权限
    
    - 系统角色不允许修改权限
    - 权限编码必须存在
    """
    result = await RoleService.add_role_permissions(role_id, permission_data.permissions)
    return success_response(data=result, message="权限添加成功")


@router.delete("/{role_id}/permissions", summary="从角色移除权限", response_model=RoleInfo)
async def remove_role_permissions(
    role_id: int,
    permission_data: RolePermissionUpdate,
    current_user: UserModel = Depends(get_current_user)
):
    """
    从角色移除权限
    
    - 系统角色不允许修改权限
    """
    result = await RoleService.remove_role_permissions(role_id, permission_data.permissions)
    return success_response(data=result, message="权限移除成功")


@router.delete("/{role_id}/permissions/clear", summary="清空角色权限", response_model=RoleInfo)
async def clear_role_permissions(
    role_id: int,
    current_user: UserModel = Depends(get_current_user)
):
    """
    清空角色所有权限
    
    - 系统角色不允许修改权限
    """
    result = await RoleService.clear_role_permissions(role_id)
    return success_response(data=result, message="角色权限已清空")


@router.patch("/batch", summary="批量更新角色")
async def batch_update_roles(
    batch_data: RoleBatchUpdate,
    current_user: UserModel = Depends(get_current_user)
):
    """
    批量更新角色状态
    
    - 系统角色不允许批量修改
    - 支持批量更新激活状态
    """
    update_data = batch_data.dict(exclude_unset=True, exclude={'ids'})
    if not update_data:
        raise BusinessException(message="没有要更新的数据")
    
    await RoleService.batch_update_roles(batch_data.ids, update_data)
    return success_response(message="批量更新成功")


@router.get("/{role_id}/check-permission/{permission_code}", summary="检查角色权限")
async def check_role_permission(role_id: int, permission_code: str):
    """检查角色是否拥有指定权限"""
    has_permission = await RoleService.check_role_permission(role_id, permission_code)
    return success_response(data={"has_permission": has_permission})


@router.post("/{role_id}/check-permissions", summary="检查角色多个权限")
async def check_role_permissions(
    role_id: int,
    permission_codes: List[str],
    check_all: bool = Query(False, description="是否检查所有权限")
):
    """检查角色是否拥有指定权限"""
    has_permission = await RoleService.check_role_permissions(role_id, permission_codes, check_all)
    return success_response(data={"has_permission": has_permission})


@router.get("/check/{role_code}", summary="检查角色编码是否存在")
async def check_role_code(role_code: str):
    """检查角色编码是否已存在"""
    role = await RoleService.get_by_code(role_code)
    exists = role is not None
    return success_response(data={"exists": exists, "role": RoleInfo.from_orm(role) if role else None})
